package ajaxjs.js;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ajaxjs.Fso;
import ajaxjs.net.Request;
import ajaxjs.service.BaseServlet;

public class JSON_Saver extends SimpleJsEngine{
	public void doAction(HttpServletRequest request, HttpServletResponse response) {	
		try{
			save(request);
			request.setAttribute("msg", "修改成功！");
			 
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute("errMsg", "修改失败！" + e.getMessage());
		}
		
		BaseServlet.output(request, response);
	}

	private void save(HttpServletRequest request) throws Exception {
		Map<String, String> hash = Request.getClient_Data(request);
		String jsonFileFullPath = load(request, hash);
		
		// 可以json.str() 的 变量名
		String topVarName = hash.get("topVarName");
		if(topVarName == null || "".equals(topVarName))
			throw new NullPointerException("没有  topVarName 参数！");
		hash.remove("topVarName");
		
		saveRAM(hash);
		
		String JSON_as_String = null;
		try {
			JSON_as_String = (String)eval("JSON.stringify(" + topVarName + ");");
		} catch (ScriptException e) {
			e.printStackTrace();
			JSON_as_String = null;
			throw new Exception("更新配置失败，不能序列化配置！");
		}
		
		if(JSON_as_String != null){
			String fileBody = topVarName + " = " + JSON_as_String + ";";
//			System.out.println(fileBody);
//			System.out.println("::::::::::::::::::2:"+jsonFileFullPath);
			try {
				Fso.writeFile(jsonFileFullPath, fileBody);
			} catch (IOException e) {
				e.printStackTrace();
				throw new Exception("更新配置失败，不能保存配置！");
			}
		}
	}
	
	private String load(HttpServletRequest request, Map<String, String> hash){
		String jsonFile = hash.get("jsonFile");
		if(jsonFile == null || "".equals(jsonFile))
			throw new NullPointerException("没有 json File 参数！");
		
		String jsonFileFullPath = Request.Mappath(request, jsonFile);

		try{
			super.load(jsonFileFullPath);
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		
		hash.remove("jsonFile");// 不需要路径
		
		return jsonFileFullPath;
	}
	
	/**
	 * 写入内存
	 * @param hash
	 * @throws ScriptException 
	 */
	private void saveRAM(Map<String, String> hash) throws ScriptException{
		String jsCode = "";
		for(String key : hash.keySet()){
			jsCode = key + " = '" + hash.get(key) + "';"; // 全部保存为 String。@todo 支持其他类型
			System.out.println(jsCode);
			try {
				eval(jsCode);
			} catch (ScriptException e) {
				e.printStackTrace();
				
				throw e;
			}
		}
	}
}
